package com.lu.widgets.component.view;

import com.lu.widgets.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.Checkable;
import android.widget.TextView;
import android.view.ViewDebug;
import android.view.accessibility.AccessibilityEvent;

/**
 * 因联想乐OS系统不支持Android原生的CheckedTextView，特重写之
 * 
 * @author 汪璐
 * @version 1.0.0.0
 * @since 2012-04-17 09:35
 */
public class CheckedTextView extends TextView implements Checkable {
	private boolean mChecked = false;
	private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };

	public CheckedTextView(Context context) {
		this(context, null);
	}

	public CheckedTextView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public CheckedTextView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		TypedArray a = context.obtainStyledAttributes(attrs,
				R.styleable.CheckedTextView, defStyle, 0);
		boolean checked = a.getBoolean(R.styleable.CheckedTextView_checked,
				false);
		setChecked(checked);
		a.recycle();
	}

	public void toggle() {
		setChecked(!mChecked);
	}

	@ViewDebug.ExportedProperty
	public boolean isChecked() {
		return mChecked;
	}

	/**
	 * <p>
	 * 改变文本视图的选中状态.
	 * </p>
	 * 
	 * @param checked
	 *            选中文本返回 true，未选中返回 false.
	 */
	public void setChecked(boolean checked) {
		if (mChecked != checked) {
			mChecked = checked;
			refreshDrawableState();
		}
	}

	@Override
	protected int[] onCreateDrawableState(int extraSpace) {
		final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
		if (isChecked()) {
			mergeDrawableStates(drawableState, CHECKED_STATE_SET);
		}
		return drawableState;
	}

	@Override
	public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
		boolean populated = super.dispatchPopulateAccessibilityEvent(event);
		if (!populated) {
			event.setChecked(mChecked);
		}
		return populated;
	}
}
